<script setup lang="jsx">
import { reactive, ref } from 'vue';
import { Button, Tag } from 'ant-design-vue';
import { parseTime } from '@/utils';
import { noticeDelete, systemnoticelist } from '@/service/api';
import Modal from '@/components/common/modal.vue';
import Search from './modules/search.vue';
import AddForm from './modules/add.vue';

const searchParams = ref({
  dictName: null,
  dictType: null,
  status: null
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'noticeId',
    dataIndex: 'noticeId',
    title: '通知编号',
    align: 'center',
    width: 100,
    checked: true,
    ellipsis: true
  },
  {
    key: 'noticeTitle',
    dataIndex: 'noticeTitle',
    title: '公告标题',
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'noticeType',
    dataIndex: 'noticeType',
    title: '公告类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.noticeType === null) {
        return null;
      }

      const tagMap = {
        1: 'success',
        2: 'error'
      };

      const label = record.noticeType == 1 ? '公告' : '通知';

      return <Tag color={tagMap[record.noticeType] || 'error'}>{label}</Tag>;
    }
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.status === null) {
        return null;
      }

      const tagMap = {
        0: 'processing',
        1: 'error'
      };

      const label = record.status == 0 ? '正常' : '关闭';

      return <Tag color={tagMap[record.status] || 'error'}>{label}</Tag>;
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建者',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    checked: true,
    width: 170,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createTime == null) {
        return null;
      }
      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'createTime',
    title: '操作',
    align: 'center',
    width: 200,
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <div>
          <Button type="link" size="small" onClick={() => add('edit', record)}>
            <icon-ic-round-edit class="align-sub text-icon" />
            修改
          </Button>
          <Button
            type="link"
            size="small"
            danger
            v-if={record.parentId !== 0}
            onClick={() => {
              deleteDept(record);
            }}
          >
            <icon-ic-round-delete class="align-sub text-icon" />
            删除
          </Button>
        </div>
      );
    }
  }
]);
const tableData = ref([]);
const loading = ref(false);

function getData() {
  loading.value = true;
  const params = {
    ...searchParams.value,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  };
  systemnoticelist(params)
    .then(({ data, error, otherData }) => {
      if (!error) {
        pagination.total = otherData?.total || 0;
        tableData.value = otherData.rows;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

getData();

function search() {
  pagination.current = 1;
  getData();
}

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      // 'background-color': record.noticeId === currentRowId.value ? 'rgba(86, 205, 243, 0.3)' : ''
      background: record.noticeId === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.noticeId === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.noticeId;
    }
  };
};

const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

function deleteDept(row) {
  let noticeId = '';
  if (row) {
    noticeId = row.noticeId;
  } else {
    noticeId = selectedRowKeys.value.join();
  }
  window.$modal.confirm({
    title: `是否确认删除序号为"${noticeId}"的数据项？`,
    onOk: () => {
      noticeDelete(noticeId).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          getData();
        }
      });
    }
  });
}

const currentRow = ref(null);
const operateType = ref('add');
const visible = ref(false);
const addFormRef = ref(null);
function add(type, row = null) {
  console.log('row :>> ', row);
  if (typeof row === 'number') {
    row = tableData.value.find(item => item.noticeId == row);
  }
  currentRow.value = row;
  operateType.value = type;
  visible.value = true;
}

function handleOk() {
  addFormRef.value.submitForm();
}

function handleClose() {
  visible.value = false;
  currentRow.value = null;
}

function handleSuccess() {
  getData();
  handleClose();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="add('add')">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectedRowKeys.length != 1"
          @click="add('edit', selectedRowKeys[0])"
        >
          <template #icon>
            <icon-ic-round-edit class="align-sub text-icon" />
          </template>
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton
          danger
          size="small"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectedRowKeys.length == 0"
          @click="deleteDept()"
        >
          <template #icon>
            <icon-ic-round-delete class="align-sub text-icon" />
          </template>
          <span class="ml-3px">删除</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        row-key="noticeId"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="pagination"
        :custom-row="customRow"
        class="h-full"
        :row-height="23"
      />
    </ACard>

    <Modal
      v-model:visible="visible"
      :title="`${operateType == 'add' ? '新增' : '修改'}公告`"
      height="500px"
      width="650px"
      :destroy-on-close="true"
      @ok="handleOk"
      @close="handleClose"
    >
      <AddForm
        ref="addFormRef"
        :dept-options="tableData"
        :current-row="currentRow"
        :operate-type="operateType"
        @success="handleSuccess"
      />
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleOk()">确定</AButton>
          <AButton @click="handleClose">取消</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style></style>
